<?php


namespace App\Utils;


use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use App\Dao\CooperativeDao;
use App\Exception\BusinessException;
use App\Utils\Wechat\OpenPlatform\OpenPlatform;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\RedisFactory;
use Monolog\Handler\IFTTTHandler;
use Swlib\Saber;
use Swlib\SaberGM;

class WxMp
{
    private $redis;

    /**
     * @Inject()
     * @var CooperativeDao
     */
    private $cooperativeDao;


    public function __construct()
    {
        $this->redis = di(RedisFactory::class)->get('default');
    }

    /**
     * @param int $cooperative_id
     * @param string $code
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function code2Session(int $cooperative_id, string $code)
    {
        //调用接口
        $openPlatform = new OpenPlatform();
        $component_access_token = $openPlatform->accessToken();

        if (!$component_access_token) {
            throw new BusinessException(ErrorCode::WXMP_GET_COMPONENT_ACCESS_TOKEN_ERROR);
        }

        $cooperative = $this->cooperativeDao->first(['id' => $cooperative_id]);
        if (!$cooperative) {
            throw new BusinessException(ErrorCode::DOMAIN_ERROR);
        }

        $component_appid = config('wechat.open_platform.app_id');
        $url = "https://api.weixin.qq.com/sns/component/jscode2session?appid=%s&js_code=%s&grant_type=authorization_code&component_appid=%s&component_access_token=%s";
        $url = sprintf($url, $cooperative->wx_mp_appid, $code, $component_appid, $component_access_token);

        try {
            $result = SaberGM::get($url);
        } catch (\Throwable $e) {
            throw new BusinessException(ErrorCode::REQUEST_ERROR);
        }

        $data = $result->getParsedJsonArray();
        if (isset($data['errcode'])) {
            switch ($data['errcode']) {
                case -1:
                    throw new BusinessException(ErrorCode::WXMP_SYSTEM_BUSY);
                    break;
                case 40029:
                    throw new BusinessException(ErrorCode::WXMP_CODE_INVALID);
                    break;
                case 45011:
                    throw new BusinessException(ErrorCode::WXMP_REQUEST_LIMIT);
                    break;
            }
        }
        return $data;
    }


}